/**
 * 
 */
package com.orange.controller.expert;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.orange.controller.BaseController;
import com.orange.dbhelp.page.Page;
import com.orange.handler.expert.AuthExamService;
import com.orange.handler.expert.AuthSpecialTaskService;
import com.orange.modules.entity.expert.AuthExam;
import com.orange.modules.entity.expert.AuthSpecialTask;
import com.orange.util.AppConfig;
import com.orange.util.ReturnCode;

/**
 * @author gaogs
 *
 * 2016-11-30
 */
@Controller
@RequestMapping("/authExam")
public class AuthExamController extends BaseController {
	
	
	private static final Logger logger = Logger.getLogger(AuthExamController.class);
	
	@Autowired
	private AuthExamService authExamService;
	
	@Autowired
	private AppConfig appconfig;
	
	@Autowired
	private AuthSpecialTaskService authSpecialTaskService;
	
	/**
	 * 查询必测专业技能
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryAuthSpecialTaskByType" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> queryAuthSpecialTaskByType(HttpServletRequest request,@RequestParam String major) throws SQLException{
		
		try{
			//String major = map.get("major");
			List<AuthSpecialTask> ls=authSpecialTaskService.queryAuthSpecialTaskByType("0",major);//必测项目
			return toResponse(ls, ReturnCode.SUCCESS, "查询必测专业技能成功");
		}catch(Exception e){
			logger.info("查询必测专业技能失败", e);
			return toResponse(null,ReturnCode.FAIL,"查询必测专业技能失败");
		}
	}
	/**
	 * 查询选测专业技能
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryAuthSpecialTaskByType1" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> queryAuthSpecialTaskByType1(HttpServletRequest request,@RequestParam String major) throws SQLException{
		
		try{
			//String major = map.get("major");
			List<AuthSpecialTask> ls=authSpecialTaskService.queryAuthSpecialTaskByType("1",major);//选测测项目
			return toResponse(ls, ReturnCode.SUCCESS, "查询选测专业技能成功");
		}catch(Exception e){
			logger.info("查询选测专业技能失败", e);
			return toResponse(null,ReturnCode.FAIL,"查询选测专业技能失败");
		}
	}
	
	/**
	 * 新建试题
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/saveAuthExamInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> saveAuthExamInfo(HttpServletRequest request,@RequestBody Map<String,String> map) throws SQLException{
		
		try{
			String url=map.get("url");//试题路径
			String subject=map.get("subject");//科目   非必传     （1:科学  2：美术  3：数学 4 ：体育  5：音乐  6：英语  7：语文）
			String taskId=map.get("taskId");//专业技能id
			String major=map.get("major");//专业
			String number=map.get("number");//编号
			if(StringUtils.isBlank(url)||StringUtils.isBlank(taskId)||StringUtils.isBlank(major)||StringUtils.isBlank(number)){
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数存在空值");
			}
			String name=url.substring(url.lastIndexOf("/")+1, url.length());
			AuthExam ae=authExamService.queryAuthExamInfoByName(name);
			if(null!=ae){
				return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "该试题已存在");
			}
			
			AuthExam a=new AuthExam();
			String nowTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			a.setTaskId(taskId);
			a.setFileName(name);
			a.setName(name);
			a.setMajor(major);
			a.setNumber(number);
			a.setFileUrl(url);
			a.setSubject(subject);
			a.setCreateTime(nowTime);
			authExamService.saveAuthExamInfo(a);
			return toResponse(null, ReturnCode.SUCCESS, "新建试题成功");
		}catch(Exception e){
			logger.info("新建试题失败", e);
			return toResponse(null,ReturnCode.FAIL,"新建试题失败");
		}
	}
	
	/**
	 * 分页查看试题
	 * 
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryAuthExamPage_review", produces = MediaType.APPLICATION_JSON_VALUE
			+ ";charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> queryAuthExamPage_review(HttpServletRequest request, @RequestBody Map<String, String> map)throws SQLException {
		
		try {
			String pageNumber = map.get("pageNumber");
			String pageSize = map.get("pageSize");
			if (StringUtils.isBlank(pageNumber))
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "数量不能为空!");
			if (StringUtils.isBlank(pageSize))
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "页数不能为空!");
			
			Page<AuthExam>  page=authExamService.queryAuthExamPage(map);
			return toResponse(page, ReturnCode.SUCCESS, "分页查看试题成功");
		} catch (Exception e) {
			logger.info("分页查看试题失败", e);
			return toResponse(null, ReturnCode.FAIL, "分页查看试题失败");
		}
		
	}

	
	/**
	 * 删除试题
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/deleteAuthExamInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> deleteAuthExamInfo(HttpServletRequest request,@RequestParam String pid) throws SQLException{
		
		try{
			if(StringUtils.isBlank(pid)){
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数存在空值");
			}
			AuthExam a=authExamService.queryAuthExamInfo(pid);
			if(null==a){
				return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "该试题不存在");
			}
			authExamService.deleteAuthExamInfo(pid);
			return toResponse(null, ReturnCode.SUCCESS, "删除试题成功");
		}catch(Exception e){
			logger.info("删除试题失败", e);
			return toResponse(null,ReturnCode.FAIL,"删除试题失败");
		}
	}

	/**
	 * 试题上传
	 * @param Filedata
	 * @return
	 */
	@RequestMapping(value="/uploadExam" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadFile(
			@RequestParam("file")MultipartFile filedata
			){
		try {
			String returnDatasUrl = null;
	  		String datasfile = appconfig.getFilePath();
	  		
	  		//取得可上传的文件类型  
	  		List<String>fileTypes = arrayToList(appconfig.getFileType().split(","));
	  		
	  		String fileName = filedata.getOriginalFilename();  
	  		//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
	  		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());  
	  		//对扩展名进行小写转换  
	  		ext = ext.toLowerCase();  
	  		/*//新的文件名
	  		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + 
	  				(int)(Math.random()*10000) + "." + ext;*/
	  		File file = null;
	  		if(!fileTypes.contains(ext)){
	  			return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"该文件类型不允许");
	  		}
	  		Long examSize=filedata.getSize();
	  		if(1.0*examSize/1024/1024>appconfig.getFileSize()){
	  			return toResponse(null,ReturnCode.FILE_SIZE_TOO_LONG,"文件大小超出限定上限");
	  		}
	  		
	  		Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH)+1;
            int d=cal.get(Calendar.DATE);
            Long nowTime=new Date().getTime();
            String pathbig=datasfile+y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
            file=new File(pathbig);
     		if(!file.exists()){
     			file.getParentFile().mkdirs();
     			file.createNewFile();
     		}
     		filedata.transferTo(file);
				
		    returnDatasUrl = y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
			return toResponse(returnDatasUrl,ReturnCode.SUCCESS,null);
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			return toResponse(null,ReturnCode.FAIL,"文件上传失败");
		}
	}
	
	   private List<String> arrayToList(String[] strs){
	    	List<String> list=new ArrayList<String>();
	    	if(strs.length>0){
	    		for(int a =0;a<strs.length;a++){
	    			list.add(strs[a].toString().trim());
	    		}
	    	}
			return list;
	    	
	    }
	   
		/**
		 * 下载文档
		 * @param request
		 * @param response
		 * @param map
		 * @return
		 */
		@RequestMapping(value="/downloadFile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public void downloadFile(HttpServletRequest request,HttpServletResponse response ,@RequestParam String examId){
			
			try {
				AuthExam a=authExamService.queryAuthExamInfo(examId);
				if(null==a){
					return;
				}
				//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		        String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		        String filepath= a.getFileUrl();
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        
		        ServletOutputStream out;  
		        File file = new File(path +filepath);  
		  
		            FileInputStream inputStream = new FileInputStream(file);  
		  
		            //3.通过response获取ServletOutputStream对象(out)  
		            out = response.getOutputStream();  
		            
		            byte[] buffer = new byte[512];  
		            int count = 0;
			         while ((count = inputStream.read(buffer)) > 0) {
			        	 out.write(buffer, 0, count);
			         } 
		            inputStream.close();  
		            out.close();  
		            out.flush();  
		  
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
			   
	   
	   
}
